<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <TodoHeader @addTodo="addTodo"/>
      <todo-list :todos="todos"/>
<!--      <todo-footer :todos="todos" :delCompleteTodos="delCompleteTodos" :selectAllTodos="selectAllTodos"></todo-footer>-->
      <todo-footer>
        <input type="checkbox" v-model="isAllCheck" slot="checkAll"/>
        <span slot="count">已完成{{ completeSize }} / 全部{{todos.length}}</span>
        <button slot="delete" class="btn btn-danger" v-show="completeSize" @click="delCompleteTodos">清除已完成任务</button>
      </todo-footer>
    </div>
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader'
import TodoList from './components/TodoList'
import TodoFooter from './components/TodoFooter'
import PubSub from 'pubsub-js'
import StorageUtil from './util/StorageUtil'
export default {
  name: 'App',
  components: {TodoHeader, TodoList, TodoFooter},
  data () {
    return {
      todos: StorageUtil.readTodos()
    }
  },
  computed: {
    completeSize () {
      return this.todos.reduce((proTotal, todo) => proTotal + (todo.complete ? 1 : 0), 0)
    },
    isAllCheck: {
      get () {
        return this.completeSize === this.todos.length && this.todos.length
      },
      set (value) {
        this.selectAllTodos(value)
      }
    }
  },
  methods: {
    addTodo (todo) {
      this.todos.unshift(todo)
    },
    delTodo (index) {
      this.todos.splice(index, 1)
    },
    // 删除所有选中的
    delCompleteTodos () {
      this.todos = this.todos.filter(todo => !todo.complete)
    },
    // 全选或者全不选
    /* eslint-disable */
    selectAllTodos (check) {
      this.todos.forEach(todo => todo.complete = check)
    }
  },
  mounted () {
    PubSub.subscribe('delTodos',(msg,data) => {
      console.log(msg);
      console.log(data);
      this.delTodo(data)
    })
  },
  watch: {
    todos: {
     /* handler: function (val) {
        // console.log(val)
        StorageUtil.saveTodos(val)
      },*/
      handler: StorageUtil.saveTodos,
      deep: true,
      immediate: true
    }
  }
}
</script>

<style scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
